import { TableColumnProps } from "ant-design-vue";
import {
  AcitivityDefItem,
  AcitivityDefStatus,
  ActivityDefType,
  CouponsScope,
  UseActivityHookResult,
} from "/@/api/main/marketing/models";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import { h, ref, watch } from "vue";
import {
  CURDAction,
  CURDDialogExpose,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
} from "/@/components/CURDDialog/models";
import TypeProductFormItem from "./TypeProductFormItem.vue";
import CustomRangeFormItem from "./CustomRangeFormItem.vue";
import dayjs from "dayjs";
import { getDeptList } from "/@/api/main/system";
import { DeptType } from "/@/api/main/system/models";
import { getActivityScope } from "/@/api/main/marketing";
import { ProductFileItem } from "/@/api/main/pis/models";
import { SelectOptionItem } from "/@/types/antd";
import { findItemByKey } from "/@/utils/treeData";
import EditorFormItem from "/@/components/EditorFormItem.vue";

export default function (): UseActivityHookResult {
  let addText = "新增活动券",
    pageTitle = "活动券定义",
    editText = "编辑活动券",
    deleteText = "确认删除该活动券吗？",
    innerColumns: TableColumnProps<Partial<AcitivityDefItem>>[] = [
      {
        title: "券名称",
        dataIndex: "couponsName",
      },
      {
        title: "券Logo",
        dataIndex: "couponsLogo",
      },
      {
        title: "券面图片",
        dataIndex: "couponsUrl",
      },
      {
        title: "券价值",
        dataIndex: "couponsValue",
      },
      {
        title: "有效期",
        dataIndex: "startPeriod",
        customRender({ record }) {
          if (record.isPermanently) {
            return "长期";
          }
          return dayjs(record.startPeriod).format("YYYY-MM-DD") + "~" + dayjs(record.endPeriod).format("YYYY-MM-DD");
        },
      },
      {
        title: "时段",
        dataIndex: "startTime",
        customRender({ record }) {
          if (record.isAllDay) {
            return "全天";
          }
          return record.startTime + "~" + record.endTime;
        },
      },
      {
        title: "用券范围",
        dataIndex: "couponsScope",
        customRender({ text }) {
          return getLabelByValueFromEnum(text, CouponsScope, "couponsScope");
        },
      },
      {
        title: "是否计算积分",
        dataIndex: "isCalcPoints",
        customRender({ text }) {
          return text ? "√" : "×";
        },
      },
      // {
      //   title: "描述",
      //   dataIndex: "description",
      // },
      {
        title: "状态",
        dataIndex: "status",
      },
      {
        title: "操作",
        key: "oper",
        fixed: "right",
        width: 100,
      },
      // {
      //   title: "出库单类型",
      //   dataIndex: "deliveryType",
      //   customRender({ text }) {
      //     return getLabelByValueFromEnum(text, DeliveryType, "deliveryType");
      //   },
      // },
      // {
      //   title: "活动起始日期",
      //   dataIndex: "deliveryDate",
      //   customRender({ text }) {
      //     return dayjs(text).format("YYYY-MM-DD");
      //   },
      // },
    ];
  const curdDialogIns = ref<CURDDialogExpose>();
  const model = ref<Partial<AcitivityDefItem>>({
    couponsName: "",
    couponsValue: null,
    couponsUrl: "",
    couponsLogo: "",
    _periodRange: { range: [], isAll: false },
    _timeRange: { range: [], isAll: false },
    couponsScope: CouponsScope.self,
    _typeProduct: { productCategoryList: [], goodsList: [] },
    unionIdList: [],
    isCalcPoints: 1,
    description: "",
  });
  const modelFormSetting = ref<FormItemData<Partial<AcitivityDefItem>>[]>([
    {
      key: "couponsName",
      required: true,
    },
    {
      key: "couponsValue",
      type: FormItemComponentType.NUMBER,
      required: true,
    },
    {
      key: "couponsUrl",
      type: FormItemComponentType.IMGUPLOAD,
      required: true,
    },
    {
      key: "couponsLogo",
      type: FormItemComponentType.IMGUPLOAD,
      required: true,
    },
    {
      key: "_periodRange",
      customComponent: h(CustomRangeFormItem),
      label: "有效期",
      required: true,
      holdRow: true,
      props: {
        isTime: false,
      },
    },
    {
      key: "_timeRange",
      customComponent: h(CustomRangeFormItem),
      label: "时段",
      required: true,
      holdRow: true,
      props: {
        isTime: true,
      },
    },
    {
      key: "couponsScope",
      type: FormItemComponentType.RADIO,
      label: "用券范围",
      required: true,
      holdRow: true,
      props: {
        options: enumToOptions(CouponsScope, "couponsScope"),
      },
    },
    {
      key: "_typeProduct",
      customComponent: h(TypeProductFormItem),
      label: "商品类别或商品",
      holdRow: true,
      required: true,
    },
    // {
    //   key: "unionIdList",
    //   type: FormItemComponentType.TREESELECT,
    //   label: "选择联盟",
    //   holdRow: true,
    //   props: {
    //     multiple: true,
    //   },
    //   required: true,
    // },
    {
      key: "unionIdList",
      type: FormItemComponentType.TREESELECT,
      label: "选择联盟",
      holdRow: true,
      required: true,
      props: {
        treeData: [],
        multiple: true,
        fieldNames: { label: "name", value: "id" },
      },
      async getData() {
        const data = await getDeptList({ type: DeptType.cooperation });
        if (data) {
          const re = findItemByKey(data, "异业联盟", { keyName: "name" });
          if (re) {
            return re.item.children || [];
          }
        }
        return [];
      },
    },
    {
      key: "isCalcPoints",
      type: FormItemComponentType.RADIO,
      label: "是否计算积分",
      holdRow: true,
      props: {
        options: [
          { value: 1, label: "计算积分" },
          { value: 0, label: "不计算积分" },
        ],
      },
    },
    {
      key: "description",
      customComponent: h(EditorFormItem),
      label: "描述",
      holdRow: true,
      props: {
        height: 250,
      },
    },
  ]);
  function innerOpen({ record, action }: CURDModalEvent<Partial<AcitivityDefItem>>) {
    handleCouponScope(model.value.couponsScope);
  }
  function beforeUpdateModel(record: AcitivityDefItem) {
    if (record.isPermanently) {
      record._periodRange = { range: ["", ""], isAll: true };
    } else if (record.startPeriod && record.endPeriod) {
      record._periodRange = {
        range: [dayjs(record.startPeriod).format("YYYY-MM-DD"), dayjs(record.endPeriod).format("YYYY-MM-DD")],
        isAll: false,
      };
    }
    if (record.isAllDay) {
      record._timeRange = { range: ["", ""], isAll: true };
    } else if (record.startTime && record.endTime) {
      record._timeRange = {
        range: [record.startTime, record.endTime],
        isAll: false,
      };
    }
    const productCategoryList: Partial<SelectOptionItem>[] = [];
    const goodsList: Partial<ProductFileItem>[] = [];
    if (record.productCategoryIdList) {
      record.productCategoryIdList.forEach((id, i) => {
        productCategoryList.push({
          value: id,
          label: record.productCategoryNameList[i],
        });
      });
    }
    if (record.goodsIdList) {
      record.goodsIdList.forEach((id, i) => {
        goodsList.push({
          id,
          name: record.goodsNameList[i],
        });
      });
    }
    record._typeProduct = {
      productCategoryList,
      goodsList,
    };
    record.isCalcPoints = record.isCalcPoints ? 1 : 0;
  }
  function handleCouponScope(val) {
    if (curdDialogIns.value) {
      if (val === CouponsScope.self) {
        curdDialogIns.value.toggleField("_typeProduct", false);
        curdDialogIns.value.toggleField("unionIdList", true);
      } else {
        curdDialogIns.value.toggleField("_typeProduct", true);
        curdDialogIns.value.toggleField("unionIdList", false);
      }
    }
  }
  watch(
    () => model.value.couponsScope,
    (val) => {
      handleCouponScope(val);
    }
  );
  function innerBeforeOk({ model, action }: CURDModalEvent<Partial<AcitivityDefItem>>) {
    if (model) {
      if (model._periodRange) {
        model.startPeriod = dayjs(model._periodRange.range[0]).valueOf();
        model.endPeriod = dayjs(model._periodRange.range[1]).valueOf();
        model.isPermanently = model._periodRange.isAll;
        delete model._periodRange;
      }
      if (model._timeRange) {
        model.startTime = model._timeRange.range[0];
        model.endTime = model._timeRange.range[1];
        model.isAllDay = model._timeRange.isAll;
        delete model._timeRange;
      }
      if (model._typeProduct) {
        model.productCategoryIdList = model._typeProduct.productCategoryList.map((el) => el.value as number);
        model.goodsIdList = model._typeProduct.goodsList.map((el) => el.id as number);
        delete model._typeProduct;
      }
      model.isCalcPoints = model.isCalcPoints === 1;
      if (action === CURDAction.CREATE) {
        model.status = AcitivityDefStatus.waiting;
      }
    }
  }
  async function getDetail(record: AcitivityDefItem) {
    const data = await getActivityScope(record.id, ActivityDefType.activityCoupon);
    return data || {};
  }
  return {
    addText,
    pageTitle,
    editText,
    deleteText,
    innerColumns,
    model,
    modelFormSetting,
    curdDialogIns,
    innerOpen,
    innerBeforeOk,
    getDetail,
    beforeUpdateModel,
  };
}
